package com.lark.algorithm.study.map;

import com.lark.algorithm.study.linkedlist.LinkedList;

/**
 * @author btmood
 * @version 1.0
 * @apiNote
 * @since 2024-05-06 21:31
 */
public class LinkedListMap<K, V> implements Map<K, V>{

    private class Node {
        public K k;
        public V v;
        private Node next;

        public Node(K K, V v, Node next) {
            this.k = K;
            this.v = v;
            this.next = next;
        }

        public Node(K k) {
            this(k, null, null);
        }

        public Node() {
            this(null, null, null);
        }

        @Override
        public String toString() {
            return k.toString() + ":" + v.toString();
        }
    }

    private Node dummyHead;
    private int size;

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node == null) {
            dummyHead.next = new Node(key, value, dummyHead.next);
            size++;
        } else {
            // 如果有该key，则覆盖value
            node.v = value;
        }
    }

    @Override
    public V remove(K key) {
        Node prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.k.equals(key)) {
                break;
            }
            prev = prev.next;
        }
        if (prev.next != null) {
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size--;
            return delNode.v;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) == null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.v;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(key);
        if (node == null) {
            throw new IllegalArgumentException("Node not found");
        }
        node.v = newValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 通过Key获取对应的Node
     * @param k
     * @return
     */
    private Node getNode(K k) {
        Node cur = dummyHead;
        while (cur != null) {
            if (cur.k.equals(k)) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
}
